package com.example.wechat.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;

@Component
public class WebSocketEventListener {

	private static final Logger log = LoggerFactory.getLogger(WebSocketEventListener.class);

	private final SimpMessageSendingOperations messagingTemplate;
	private final Map<String, String> userSessionMap = new ConcurrentHashMap<>();

	public WebSocketEventListener(SimpMessageSendingOperations messagingTemplate) {
		this.messagingTemplate = messagingTemplate;
	}

	/**
	 * 处理WebSocket连接事件
	 */
	@EventListener
	public void handleWebSocketConnectListener(SessionConnectEvent event) {
		StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

		String sessionId = headerAccessor.getSessionId();
		String userId = headerAccessor.getFirstNativeHeader("userId");
		String user = headerAccessor.getUser() != null ? headerAccessor.getUser().getName() : "anonymous";

		System.out.println("用户连接: " + user + " (会话ID: " + sessionId + ")");
		System.out.println("用户id: " + userId);

		// 可以在这里记录用户上线状态
		// 发送用户上线通知给相关用户
		if (!"anonymous".equals(user)) {
			messagingTemplate.convertAndSend("/topic/user.online", "用户 " + user + " 已上线");
		}
		if (userId != null) {
			userSessionMap.put(sessionId, userId);
			log.info("用户 {} 已连接, sessionId: {}", userId, sessionId);

			// 通知好友用户上线状态
			messagingTemplate.convertAndSend("/topic/user-online", Map.of("userId", userId, "online", true));
		}
	}

	/**
	 * 处理WebSocket断开连接事件
	 */
	@EventListener
	public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
		StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

		String sessionId = headerAccessor.getSessionId();
		String user = headerAccessor.getUser() != null ? headerAccessor.getUser().getName() : "anonymous";
		String userId = userSessionMap.remove(sessionId);

		System.out.println("用户断开连接: " + user + " (会话ID: " + sessionId + ")");

		// 可以在这里记录用户下线状态
		// 发送用户下线通知给相关用户
		if (!"anonymous".equals(user)) {
			messagingTemplate.convertAndSend("/topic/user.offline", "用户 " + user + " 已下线");
		}
		if (userId != null) {
			log.info("用户 {} 已断开连接, sessionId: {}", userId, sessionId);

			// 通知好友用户下线状态
			messagingTemplate.convertAndSend("/topic/user-offline", Map.of("userId", userId, "online", false));
		}
	}

	/**
	 * 检查用户是否在线
	 */
	public boolean isUserOnline(String userId) {
		return userSessionMap.containsValue(userId);
	}

	/**
	 * 获取在线用户列表
	 */
	public Map<String, String> getOnlineUsers() {
		return new ConcurrentHashMap<>(userSessionMap);
	}

	/**
	 * 处理订阅事件
	 */
	@EventListener
	public void handleSubscriptionEvent(SessionSubscribeEvent event) {
		StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());

		String sessionId = headerAccessor.getSessionId();
		String destination = headerAccessor.getDestination();
		String user = headerAccessor.getUser() != null ? headerAccessor.getUser().getName() : "anonymous";

		System.out.println("用户订阅: " + user + " 订阅了 " + destination + " (会话ID: " + sessionId + ")");

		// 可以在这里处理订阅逻辑，比如权限验证
		if (destination != null && destination.startsWith("/topic/group.")) {
			// 验证用户是否有权限订阅该群聊
			String groupId = destination.replace("/topic/group.", "");
			System.out.println("用户 " + user + " 请求订阅群聊 " + groupId);
		}
	}
}